// pages/Device_details/Device_details.js
import api from "../../Sendingmethod/Sendingmethod"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 选中index
        s_index: 0,
        //list的文字
        shopindex: "",
        listarr_one: [{
                text: '设备编号',
                value: "ZQM20241120",
                title: 'serialnum'
            },
            {
                text: '设备名称',
                value: "测试1",
                title: 'name'
            },
            {
                text: '实时库存',
                value: "100",
                title: 'stock'
            },
            {
                text: '省/市/区（县）',
                value: "重庆市/江北区",

            },
            {
                text: '详细地址',
                value: "观音桥街道步行街卤校长火锅"
            },

        ],
        emid: "",
        emdata: "",
        show: false,
        //1 库存 2 删除 3修改
        type: '',

        arrbox: [{
            type: 1,
            text: '增加'
        }, {
            type: -1,
            text: '减少'
        }],
        setindex: 1,
        stocknum: "",
        pricenum: "",
        amount: "",
        did: "",
        triggered: true
    },
    /**
     * 
     * 跳转
     */
    goto(e) {
        console.log(e.target.dataset.id);
        let data = e.target.dataset.id
        wx.navigateTo({
            url: `/pages/Select_product/Select_product?emid=${data}`,
        })
    },
    opening() {
        if (this.data.s_index) {
            wx.navigateTo({
                url: `/pages/Device_operation/Device_operation?emid=${this.data.emdata.id}`
            })
        } else {
            this.opemdoor()
        }

    },
    moshixunz(e) {
        console.log('库存选择', e.target.dataset.index);
        this.setData({
            setindex: e.target.dataset.index
        })
    },
    //库存输入
    inputboxooo(e) {
        console.log(e.detail.value);
        this.setData({
            stocknum: e.detail.value
        })
    },
    //修改金额输入
    inputboxaaaa(e) {
        console.log(e.detail.value);

        this.setData({
            pricenum: e.detail.value
        })
    },
    handleInput(e) {
        let value = e.detail.value;

        // 去除非数字和小数点的字符
        value = value.replace(/[^\d.]/g, '');

        // 防止出现多个小数点
        const dotCount = (value.match(/\./g) || []).length;
        if (dotCount > 1) {
            // 只保留第一个小数点及其之前的部分和其后的数字
            const firstDotIndex = value.indexOf('.');
            value = value.slice(0, firstDotIndex + 1) + value.slice(firstDotIndex + 1).replace(/\./g, '');
        }

        // 处理小数点后的位数，只保留两位
        const dotIndex = value.indexOf('.');
        if (dotIndex !== -1) {
            value = value.slice(0, dotIndex + 3);
        }

        // 去除开头多余的 0，除非只有一个 0 或者是 0. 开头
        if (value.startsWith('0') && value.length > 1 && !value.startsWith('0.')) {
            value = value.slice(1);
        }

        this.setData({
            pricenum: value
        });

    },
    //修改金额
    async xiugaiPrice() {
        wx.showLoading({
            mask: true
        })
        if (this.data.pricenum <= 0) {
            wx.showToast({
                title: '请输入大于0的数字',
                icon: "error",
                duration: 2000
            })
            wx.hideLoading()
            return
        } else {
            this.setData({
                show: false
            })
            try {
                let res = await api.changePrice({
                    device_id: this.data.emdata.id,
                    goods_id: this.data.emdata.goods_list[0].goods_id,
                    price: Number(this.data.pricenum)
                })
                console.log(res, '修改金额反馈');
                if (res.code == 0) {
                    wx.hideLoading()
                    wx.showToast({
                        title: '修改成功',
                        icon: "success",
                        duration: 2000
                    })
                    this.getdevicedetail()
                } else {
                    wx.hideLoading()
                }
            } catch (error) {
                wx.hideLoading()
                wx.showToast({
                    title: '请求失败',
                    icon: "error",
                    duration: 2000
                })
            }
        }



    },
    /**
     * xialshuax 下拉刷新
     */
    xialshuax() {
        wx.showLoading({
            mask: true
        })
        console.log('下拉刷新触发');
        this.getdevicedetail()
        setTimeout(() => {
            wx.hideLoading()
            this.setData({
                triggered: false
            })
        }, 1000)
    },
    //补货开门
    async opemdoor() {
        wx.showLoading({
            title: "开门中",
            mask: true
        })
        try {
            let res = await api.openDoorone({
                device_id: this.data.emdata.id,
            })
            console.log(res);
            if (res.code == 0) {
                wx.showToast({
                    title: '开门成功',
                    icon: "success",
                    duration: 2000
                })
                wx.hideLoading()

            } else {
                wx.hideLoading()

                wx.showToast({
                    title: '开门失败',
                    icon: "success",
                    duration: 2000
                })

            }
        } catch (error) {
            wx.showToast({
                title: '请求失败',
                icon: "success",
                duration: 2000
            })
            wx.hideLoading()
        }

    },

    /**
     * 关闭
     */
    guanbi() {
        this.setData({
            show: false
        })
    },


    /**
     * 
     * 增减库存
     */
    async zenjiajians() {
        wx.showLoading({
            mask: true
        })
        this.setData({
            show: false
        })
        //判断


        function isPositiveInteger(num) {
            return Number.isInteger(num) && num > 0;
        }
        if (isPositiveInteger(Number(this.data.stocknum))) {

            console.log('是正整数', isPositiveInteger(this.data.stocknum));
        } else {
            console.log('非正整数', isPositiveInteger(this.data.stocknum));
            wx.showToast({
                title: '请输入正整数',
                icon: "error",
                duration: 2000
            })
            return
        }
        // let num = setSign(this.data.stocknum, this.data.setindex);
        try {
            let res = await api.incDecStock({
                device_id: this.data.emdata.id,
                goods_id: this.data.emdata.goods_list[0].goods_id,
                stock: Number(this.data.stocknum)
            })
            console.log(res, '增减库存');
            if (res.code == 0) {
                wx.showToast({
                    title: '操作成功',
                    icon: 'error',
                    duration: 2000
                })
                wx.hideLoading()
                this.getdevicedetail()
            } else {
                wx.showToast({
                    title: '操作失败',
                    icon: 'error',
                    duration: 2000
                })
                wx.hideLoading()
            }

        } catch (error) {
            wx.hideLoading()
            wx.showToast({
                title: "请求失败",
                icon: 'error',
                duration: 2000
            })
        }
    },

    /**
     *打开删除弹窗
     */
    opentanchuang(e) {
        console.log(e.target.dataset.index, e);
        this.setData({
            show: true,
            type: e.target.dataset.index,
            stocknum: "",
            shopindex: e.target.dataset.obj.price

        })

    },
    onRefresh: function () {
        //导航条加载动画
        wx.showNavigationBarLoading()
        //loading 提示框
        wx.showLoading({
            title: 'Loading...',
        })
        console.log("下拉刷新啦");
        setTimeout(function () {
            wx.hideLoading();
            wx.hideNavigationBarLoading();
            //停止下拉刷新
            wx.stopPullDownRefresh();
        }, 2000)
    },
    onPullDownRefresh: function () {
        this.onRefresh();
    },

    closebox() {
        this.setData({
            show: false
        })
    },
    /**
     * 
     * 删除商品
     */
    async deleshop() {
        wx.showLoading({
            mask: true
        })
        this.setData({
            show: false
        })

        try {
            let res = await api.deleteGoods({
                device_id: this.data.emdata.id,
                goods_id: this.data.emdata.goods_list[0].goods_id
            })
            console.log(res);
            if (res.code == 0) {
                wx.showToast({
                    title: '删除成功',
                    icon: 'error',
                    duration: 2000
                })
                wx.hideLoading()

                this.getdevicedetail()
            } else {
                wx.showToast({
                    title: '删除失败',
                    icon: 'error',
                    duration: 2000
                })
                wx.hideLoading()
            }

        } catch (error) {
            wx.hideLoading()
            wx.showToast({
                title: "请求失败",
                icon: 'error',
                duration: 2000
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.emid) {
            console.log(options, '传值');
            this.setData({
                emid: JSON.parse(options.emid)
            })
        }
        if (options.did) {
            console.log(options, '传值');
            this.setData({
                did: options.did
            })
        }

    },
    /**
     * 选中
     */
    selectbox(e) {
        if (this.data.s_index !== e.target.dataset.index) {
            this.setData({
                s_index: e.target.dataset.index
            })
        }

    },
    /**
     * 获取设备详情
     */
    async getdevicedetail() {
        let res = await api.devicedetail({
            id: this.data.emid,
            serialnum: this.data.did
        })
        if (res.code == 0) {
            console.log(res, '设备详情');

            this.setData({
                emdata: res.data,
                stocknum: res.data.goods_list.length > 0 ? res.data.goods_list[0].remain : ''
            })
            // console.log(this.data.stocknum);
        }
    },
    /**
     * 补货开门
     */


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getdevicedetail()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})